// pages/myPan/settings/editAddress/editAddress.js
var util = require('../../../../utils/util.js');
import api from '../../../../api/api.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: "",
    phone: "",
    ADDRESS_1_STR: "",
    REGION_PROVINCE: "",
    REGION_COUNTRY: "",
    REGION_CITY: "",
    ADDRESS: "",
    addressList: "",
    loginInfo: [],
    addressType: 1
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.data.addressType = options.type
    wx.setNavigationBarTitle({
      title: options.type == 0 ? "编辑收货地址" : "新增收货地址"
    })
    //获取用户信息
    api.getUser({
      done: (user) => {
        that.data.loginInfo = user
        //编辑获取已填地址
        if (options.a_id) {
          that.onLoadData(options.a_id);
        }
      }
    })
  },
  onLoadData: function (id) {
    var that = this;
    var jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":"' + that.data.loginInfo.id + '","id":"' + id + '"}}';
    //获取地址列表
    api.getAddressList({
      method: 'POST',
      data: {
        REQ_MESSAGE: jsonStr
      },
      success: (res) => {
        if (res.rows.length > 0) {
          that.setData({
            id: res.rows[0].id,
            name: res.rows[0].users_name,
            phone: res.rows[0].users_phone,
            REGION_PROVINCE: res.rows[0].province,
            REGION_CITY: res.rows[0].city,
            REGION_COUNTRY: res.rows[0].area,
            ADDRESS_1_STR: res.rows[0].province + "-" + res.rows[0].city + "-" + res.rows[0].area,
            ADDRESS: res.rows[0].detailed_address
          });
        }
      }
    })
  },
  bingAddressTap: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        var regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
        var REGION_PROVINCE = [];
        var addressBean = {
          REGION_PROVINCE: null,
          REGION_COUNTRY: null,
          REGION_CITY: null,
          ADDRESS: null
        };

        function regexAddressBean(address, addressBean) {
          regex = /^(.*?[市州]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
          var addxress = regex.exec(address);
          addressBean.REGION_CITY = addxress[1];
          addressBean.REGION_COUNTRY = addxress[2];
          addressBean.ADDRESS = addxress[3] + "(" + res.name + ")";
        }
        if (!(REGION_PROVINCE = regex.exec(res.address))) {
          regex = /^(.*?(省|自治区))(.*?)$/;
          REGION_PROVINCE = regex.exec(res.address);
          addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
          regexAddressBean(REGION_PROVINCE[3], addressBean);
        } else {
          addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
          regexAddressBean(res.address, addressBean);
        }
        console.log(addressBean);
        that.setData({
          ADDRESS_1_STR: addressBean.REGION_PROVINCE + "-" +
            addressBean.REGION_CITY + "-" +
            addressBean.REGION_COUNTRY
        });
        that.setData(addressBean);
      }
    })
  },
  onInput: function (e) {
    switch (e.target.dataset.name) {
      case "name":
        this.setData({
          name: util.trim(e.detail.value)
        });
        break;
      case "phone":
        this.setData({
          phone: util.trim(e.detail.value)
        });
        break;
      case "addressDetail":
        this.setData({
          ADDRESS: util.trim(e.detail.value)
        });
        break;
    }
  },
  onSetAddress: function () {
    var self = this;
    if (util.trim(self.data.name) == "" && !self.data.name) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: "#e30c26",
        content: '请输入收货人姓名'
      })
      return;
    }
    if (util.trim(self.data.phone) == "" && !self.data.name) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: "#e30c26",
        content: '请输入手机号码'
      })
      return;
    }
    if (!util.check.phone(self.data.phone)) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: "#e30c26",
        content: '手机号码格式不正确'
      })
      return;
    }
    if (util.trim(self.data.ADDRESS_1_STR) == "" && !self.data.ADDRESS_1_STR) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: "#e30c26",
        content: '请选择收货地址'
      })
      return;
    }
    if (util.trim(self.data.ADDRESS) == "" && !self.data.ADDRESS) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: "#e30c26",
        content: '请输入详细收货地址'
      })
      return;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    var jsonStr = ''
    if (self.data.addressType == 1) {
      jsonStr = '{ "REQ_HEAD": { "SIGN": "null" }, "REQ_BODY": { "province": "' + self.data.REGION_PROVINCE + '", "city": "' + self.data.REGION_CITY + '", "area": "' + self.data.REGION_COUNTRY + '", "name": "' + self.data.name + '", "phone": "' + self.data.phone + '","userId": "' + self.data.loginInfo.id + '","detailedAddress":"' + self.data.ADDRESS + '","remark":"" } }'
      api.setAddress({
        method: 'POST',
        data: {
          REQ_MESSAGE: jsonStr
        },
        complete: (res) => {
          if (res.statusCode == 200) {
            if (res.data.REP_BODY.RSPCOD == "000000") {
              var jsonData = {};
              jsonData.users_name = self.data.name;
              jsonData.users_phone = self.data.phone;
              jsonData.province = self.data.REGION_PROVINCE;
              jsonData.city = self.data.REGION_CITY;
              jsonData.area = self.data.REGION_COUNTRY;
              jsonData.detailed_address = self.data.ADDRESS;
              jsonData.default_address = 0;
              jsonData.id = res.data.REP_BODY.SUCCESSID;
              jsonData.addressType = self.data.addressType;
              wx.setStorage({
                key: 'addAddress',
                data: jsonData,
                success: function () {
                  wx.navigateBack();
                  // wx.redirectTo({
                  //   url: '../address/address'
                  // })
                }
              })
            } else {
              //失败处理
              wx.showToast({
                title: '添加失败!',
                image: '/image/ico/error-ico.png',
                duration: 2000
              })
            }
          } else {
            wx.showToast({
              title: '添加失败!',
              image: '/image/ico/error-ico.png',
              duration: 2000
            })
          }
        }
      })
    } else {
      jsonStr = '{ "REQ_HEAD": { "SIGN": "null" }, "REQ_BODY": { "province": "' + self.data.REGION_PROVINCE + '", "city": "' + self.data.REGION_CITY + '", "area": "' + self.data.REGION_COUNTRY + '", "name": "' + self.data.name + '", "phone": "' + self.data.phone + '","id": "' + self.data.id + '","userId": "' + self.data.loginInfo.id + '","detailedAddress":"' + self.data.ADDRESS + '","remark":"" } }'
      api.upDataAddress({
        method: 'POST',
        data: {
          REQ_MESSAGE: jsonStr
        },
        complete: (res) => {
          if (res.statusCode == 200) {
            if (res.data.REP_BODY.RSPCOD == "000000") {
              var jsonData = {};
              jsonData.users_name = self.data.name;
              jsonData.users_phone = self.data.phone;
              jsonData.province = self.data.REGION_PROVINCE;
              jsonData.city = self.data.REGION_CITY;
              jsonData.area = self.data.REGION_COUNTRY;
              jsonData.detailed_address = self.data.ADDRESS;
              jsonData.id = self.data.id;
              jsonData.addressType = self.data.addressType;
              wx.setStorage({
                key: 'addAddress',
                data: jsonData,
                success: function () {
                  wx.redirectTo({
                    url: '../address/address'
                  })
                }
              })
            } else {
              //失败处理
              wx.showToast({
                title: '编辑失败!',
                image: '/image/ico/error-ico.png',
                duration: 2000
              })
            }
          } else {
            wx.showToast({
              title: '编辑失败!',
              image: '/image/ico/error-ico.png',
              duration: 2000
            })
          }
        }
      })
    }
  }
})